<template>
  <Dialog :title="'备款转账'" v-model="dialogVisible" width="800px" @close="handleClose">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="loading"
    >
      <el-form-item label="转出商家">
        <div class="merchant-info-card">
          <div class="merchant-name">{{ fromMerchant?.merchantName || '未选择商家' }}</div>
          <div class="merchant-balance">总余额: <span class="balance-amount">{{ fromMerchant?.balance || 0 }}元</span></div>
        </div>
      </el-form-item>
      
      <el-form-item label="转出账户" prop="fromAccountId">
        <el-select 
          v-model="formData.fromAccountId" 
          placeholder="请选择转出账户（备款账户）" 
          filterable 
          :loading="accountLoading"
          class="!w-100%"
          clearable
          @change="handleFromAccountChange"
        >
          <el-option
            v-for="item in fromAccountList"
            :key="item.id"
            :label="`备款账户 - 余额: ${item.balance || 0}元 | 账户类型: ${getAccountTypeName(item.accountType)} | 广告主: ${item.accountId}`"
            :value="item.id"
            :disabled="(item.balance || 0) <= 0"
          />
        </el-select>
        <div v-if="selectedFromAccount" class="mt-2 text-sm text-gray-600">
          可转出金额: <span class="font-semibold text-blue-600">{{ selectedFromAccount.balance || 0 }}元</span>
        </div>
      </el-form-item>
      
      <el-form-item label="转入账户" prop="toAccountId">
        <el-select 
          v-model="formData.toAccountId" 
          placeholder="请选择转入账户" 
          filterable 
          :loading="toAccountLoading"
          class="!w-100%"
          clearable
          :disabled="!formData.fromAccountId"
        >
          <el-option
            v-for="item in toAccountList"
            :key="item.id"
            :label="`账户类型: ${getAccountTypeName(item.accountType)} | 广告主: ${item.accountId} | 余额: ${item.balance || 0}元`"
            :value="item.id"
          />
        </el-select>
        <div v-if="!formData.fromAccountId" class="mt-2 text-sm text-gray-500">
          请先选择转出账户
        </div>
      </el-form-item>
      
      <el-form-item label="转账金额" prop="amount">
        <el-input-number
          v-model="formData.amount"
          :min="0.01"
          :max="Math.max(0.01, selectedFromAccount?.balance || 0.01)"
          :precision="2"
          placeholder="请输入转账金额"
          style="width: 100%"
          :disabled="!selectedFromAccount || (selectedFromAccount?.balance || 0) <= 0"
        />
        <div v-if="selectedFromAccount" class="mt-2 text-sm text-gray-600">
          最大可转金额: <span class="font-semibold">{{ selectedFromAccount.balance || 0 }}元</span>
        </div>
        <div v-if="selectedFromAccount && (selectedFromAccount?.balance || 0) <= 0" class="mt-2 text-sm text-red-500">
          该账户余额不足，无法转账
        </div>
      </el-form-item>
      
      <el-form-item label="转账备注">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入转账备注（可选）"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="转账说明">
        <el-alert
          title="备款转账：将从备款账户转出资金到指定的目标账户"
          type="info"
          :closable="false"
          show-icon
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取 消</el-button>
      <el-button 
        type="primary" 
        @click="handleSubmit" 
        :loading="submitLoading"
        :disabled="!canSubmit"
      >
        确认转账
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { MerchantApi, MerchantVO } from '@/api/juliang/merchant'
import { AccountBalanceApi, AccountBalanceVO } from '@/api/juliang/accountbalance'
import { getDictLabel, DICT_TYPE } from '@/utils/dict'

defineOptions({ name: 'TransferForm' })

const message = useMessage()

// 获取账户类型中文名称
const getAccountTypeName = (accountType: number) => {
  return getDictLabel(DICT_TYPE.JULIANG_ACCOUNT_TYPE, accountType) || '未知类型'
}

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emits = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emits('update:modelValue', value)
})

const formRef = ref()
const loading = ref(false)
const submitLoading = ref(false)
const fromMerchant = ref<MerchantVO | null>(null)

// 账户列表相关
const fromAccountList = ref<AccountBalanceVO[]>([])
const toAccountList = ref<AccountBalanceVO[]>([])
const accountLoading = ref(false)
const toAccountLoading = ref(false)

// 选中的转出账户
const selectedFromAccount = computed(() => {
  return fromAccountList.value.find(item => item.id === formData.fromAccountId)
})

// 是否可以提交
const canSubmit = computed(() => {
  const fromAccount = selectedFromAccount.value
  const hasValidBalance = fromAccount && (fromAccount.balance || 0) > 0
  
  return formData.fromAccountId && 
         formData.toAccountId && 
         formData.amount && 
         formData.amount > 0 && 
         hasValidBalance &&
         formData.amount <= (fromAccount?.balance || 0)
})

// 表单数据
const formData = reactive({
  fromAccountId: undefined as number | undefined,
  toAccountId: undefined as number | undefined,
  amount: undefined as number | undefined,
  remark: ''
})

// 表单验证规则
const formRules = reactive({
  fromAccountId: [{ required: true, message: '请选择转出账户', trigger: 'change' }],
  toAccountId: [{ required: true, message: '请选择转入账户', trigger: 'change' }],
  amount: [
    { required: true, message: '请输入转账金额', trigger: 'blur' },
    { 
      validator: (rule: any, value: number, callback: any) => {
        if (!value || value <= 0) {
          callback(new Error('转账金额必须大于0'))
        } else if (selectedFromAccount.value && value > selectedFromAccount.value.balance) {
          callback(new Error(`转账金额不能超过可用余额${selectedFromAccount.value.balance}元`))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
})

/** 获取转出账户列表（备款账户） */
const getFromAccountList = async () => {
  if (!fromMerchant.value?.id) return
  
  accountLoading.value = true
  try {
    // 使用商家API获取该商家的账户列表，专门查询备款账户
    const data = await MerchantApi.getMerchantAccounts({
      pageNo: 1,
      pageSize: 100,
      merchantId: fromMerchant.value.id,
      queryBeikuanAccount: true  // 查询备款账户
    })
    
    if (data?.list?.length > 0) {
      // 只显示有余额的备款账户
      fromAccountList.value = data.list.filter(item => (item.balance || 0) > 0)
      
      // 自动选择第一个账户
      if (fromAccountList.value.length > 0) {
        formData.fromAccountId = fromAccountList.value[0].id
        // 选择转出账户后自动获取转入账户列表
        nextTick(() => {
          getToAccountList()
        })
      }
    } else {
      fromAccountList.value = []
    }
  } catch (error) {
    console.error('获取转出账户列表失败:', error)
    message.error('获取转出账户列表失败')
    fromAccountList.value = []
  } finally {
    accountLoading.value = false
  }
}

/** 获取转入账户列表 */
const getToAccountList = async () => {
  if (!formData.fromAccountId) return
  
  toAccountLoading.value = true
  try {
    // 获取所有账户列表（非备款账户）
    const data = await AccountBalanceApi.getAccountBalancePage({
      pageNo: 1,
      pageSize: 100,
      merchantId: fromMerchant.value?.id,
      queryBeikuanAccount: false
    })
    
    if (data?.list?.length > 0) {
      // 排除转出账户，只显示其他账户
      toAccountList.value = data.list.filter(item => item.id !== formData.fromAccountId)
    } else {
      toAccountList.value = []
    }
  } catch (error) {
    console.error('获取转入账户列表失败:', error)
    message.error('获取转入账户列表失败')
    toAccountList.value = []
  } finally {
    toAccountLoading.value = false
  }
}

/** 处理转出账户变化 */
const handleFromAccountChange = (accountId: number | undefined) => {
  // 清空转入账户选择
  formData.toAccountId = undefined
  formData.amount = undefined
  
  // 获取转入账户列表
  if (accountId) {
    getToAccountList()
  } else {
    toAccountList.value = []
  }
}

/** 初始化数据 */
const initData = (merchant: MerchantVO) => {
  fromMerchant.value = merchant
  resetFormData()
  
  // 获取转出账户列表
  getFromAccountList()
}

/** 重置表单数据 */
const resetFormData = () => {
  formData.fromAccountId = undefined
  formData.toAccountId = undefined
  formData.amount = undefined
  formData.remark = ''
  
  fromAccountList.value = []
  toAccountList.value = []
}

/** 关闭表单 */
const handleClose = () => {
  emits('update:modelValue', false)
  resetForm()
}

/** 重置表单 */
const resetForm = () => {
  formRef.value?.resetFields()
  fromMerchant.value = null
  resetFormData()
}

/** 提交表单 */
const handleSubmit = async () => {
  try {
    // 校验表单
    await formRef.value.validate()
    
    // 获取账户信息用于确认
    const fromAccount = selectedFromAccount.value
    const toAccount = toAccountList.value.find(item => item.id === formData.toAccountId)
    
    if (!fromAccount || !toAccount) {
      message.error('账户信息获取失败，请重试')
      return
    }
    
    // 检查余额是否充足
    if ((fromAccount.balance || 0) < (formData.amount || 0)) {
      message.warning(
        `备款余额不足！当前备款余额：${fromAccount.balance || 0}元，转出金额：${formData.amount || 0}元，请调整转账金额或先进行充值。`
      )
      return
    }
    
    // 二次确认
    await message.confirm(
      `确认备款转账：\n` +
      `转出：${fromMerchant.value?.merchantName} 备款账户 (余额: ${fromAccount.balance}元)\n` +
      `转入：${getAccountTypeName(toAccount.accountType)}账户 | 广告主: ${toAccount.accountId}\n` +
      `金额：${formData.amount}元`
    )
    
    submitLoading.value = true
    
    // 调用转账API
    await AccountBalanceApi.transferBalance({
      fromAccountId: formData.fromAccountId!,
      toAccountId: formData.toAccountId!,
      amount: formData.amount!,
      remark: formData.remark || `备款转账：从${fromMerchant.value?.merchantName}的备款账户转出`
    })
    
    message.success('备款转账成功')
    handleClose()
    emits('success')
  } catch (error) {
    console.error('备款转账失败:', error)
    if (error !== 'cancel') {
      message.error('备款转账失败，请重试')
    }
  } finally {
    submitLoading.value = false
  }
}

/** 打开表单 */
const open = (merchant: MerchantVO) => {
  initData(merchant)
  emits('update:modelValue', true)
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
:deep(.el-input-number) {
  width: 100%;
}

.text-gray-600 {
  color: #6b7280;
}

.text-gray-500 {
  color: #9ca3af;
}

.text-blue-600 {
  color: #2563eb;
}

.text-red-500 {
  color: #ef4444;
}

.font-semibold {
  font-weight: 600;
}

.merchant-info-card {
  padding: 12px 16px;
  background-color: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.merchant-name {
  margin-bottom: 6px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.merchant-balance {
  font-size: 14px;
  color: #606266;
}

.balance-amount {
  font-weight: 600;
  color: #409eff;
}
</style> 